package face.pay.api.payter.channel.paytype.alilpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.face.pay.AliPayConfig;
import face.pay.api.alipay.param.AliPayParam;
import face.pay.api.alipay.param.TradeParam;
import face.pay.api.payter.channel.paytype.AbstractPayType;
import face.pay.api.payter.channel.paytype.alilpay.api.ApiAliOrderQuery;
import face.pay.constant.OrderType;
import face.pay.constant.PayType;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.OemInfo;
import face.pay.entity.OrderInfo;
import face.pay.entity.StoreInfo;
import face.pay.util.MathUtil;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝刷脸支付
 */
@Component
@Slf4j
public class AliJsPay extends AbstractPayType {

    @Autowired
    ApiAliOrderQuery apiAliOrderQuery;

    @Override
    public ResultMessage pay(JSONObject json) {

        log.info("支付宝js支付:" + json.toJSONString());

        try {

            AliPayParam payParam =  json.toJavaObject(AliPayParam.class);

            StoreInfo storeInfo = this.storeInfoDao.getById(payParam.getStoreId());

            EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.getById(storeInfo.getEnterpriseId());

            Integer sqlStatus = enterpriseInfo.getSqrStatus();
            if(new Integer(1).equals(sqlStatus)){

                Long sqrLimit = enterpriseInfo.getSqrLimit()==null?Long.valueOf(0):enterpriseInfo.getSqrLimit();


                if(sqrLimit.compareTo(Long.valueOf(0))==1){

                    if(payParam.getTotal_fee().compareTo(sqrLimit)==1){
                        return ResultMessage.createFail("收款超限最大支付金额为："+MathUtil.transForMoney(sqrLimit)+"/元");
                    }

                }
            }else {
                return ResultMessage.createFail("此功能已关闭，请用其他方式支付");
            }

            String safe = this.paySafe(payParam.getTerminalId(),payParam.getCardDetailId(), payParam.getTotal_fee(),payParam.getAct_fee());

            if (StringUtils.isNotBlank(safe)) {
                log.info("交易信息不正确，中断支付");
                return ResultMessage.createFail("交易信息不正确，中断支付");
            } else {
                Integer oemId = enterpriseInfo.getOemId();
                OemInfo oemInfo = this.oemInfoDao.getOemInfoById(oemId);
                AliPayConfig aliConfig =  this.iWxPayConfigServer.getAliConfig(oemId);

                if(aliConfig.validate()){
                    String aliUserId = enterpriseInfo.getAliUserId();

                    String app_auth_token = enterpriseInfo.getAliToken();

                    if (StringUtils.isBlank(aliUserId) && StringUtils.isBlank(app_auth_token)) {
                        log.info("支付宝用户身份信息错误");
                        return ResultMessage.createFail("支付宝商家用户身份信息错误");
                    }

                    String body = storeInfo.getName() + "-线下支付";

                    OrderInfo orderInfo =  new OrderInfo();
                    orderInfo.setStoreId(payParam.getStoreId());
                    orderInfo.setUserId(enterpriseInfo.getUserId());
                    orderInfo.setOemId(oemId);
                    orderInfo.setType(OrderType.ALIPAY);
                    orderInfo.setChannelCode(payParam.getChannelCode());
                    orderInfo.setPayType(PayType.QRCODE);
                    orderInfo.setScene(1);
                    orderInfo.setSubsidyMoney(new Long(0));
                    orderInfo.setTerminalId(payParam.getTerminalId());
                    orderInfo.setTotalFee(payParam.getTotal_fee());
                    orderInfo.setIp(payParam.getIp());
                    orderInfo.setStatus(0);

                    this.orderInfoDao.insert(orderInfo);

                    String out_trade_no = String.valueOf(orderInfo.getId());


                    Double money =     MathUtil.transForMoney(new Long(payParam.getAct_fee()));

                    AlipayClient alipayClient = new DefaultAlipayClient(
                            "https://openapi.alipay.com/gateway.do", aliConfig.getAppid(), aliConfig.getAppKey(), "json", "GBK", aliConfig.getAliPublicKey(), "RSA2");

                    AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类


                    TradeParam tradeParam = new TradeParam();

                    tradeParam.setOut_trade_no(out_trade_no);

                    tradeParam.setScene("bar_code");
                    tradeParam.setSeller_id(aliUserId);

                    tradeParam.setSubject(body);

                    tradeParam.setStore_id(String.valueOf(payParam.getStoreId()));
                    tradeParam.setTimeout_express("1m");
                    tradeParam.setTotal_amount(money.toString());

                    Map<String,String> extend_params =  new HashMap<String,String>();
                    extend_params.put("sys_service_provider_id",aliConfig.getAliProviderId());
                    tradeParam.setExtend_params(extend_params);

                    String jsonContent = JSON.toJSONString(tradeParam);
                    request.setBizContent(jsonContent);
                    request.putOtherTextParam("app_auth_token",enterpriseInfo.getAliToken());

                    log.info("发送请求："+jsonContent);
                    AlipayTradePrecreateResponse response = alipayClient.execute(request);
                    log.info("返回结果："+JSON.toJSONString(response));
                    if (response.isSuccess()) {
                        if (response.getCode().equals("10000")) {

                            String qrCode =   response.getQrCode();

                            Map<String,String> data = new HashMap<>();

                            orderInfo.setActFee(payParam.getAct_fee());
                            orderInfo.setActInnerFee(payParam.getAct_fee());
                            orderInfo.setPayCode(qrCode);

                            this.orderInfoDao.updatePayInfo(orderInfo);

                            apiAliOrderQuery.orderStatusCheck(orderInfo,aliConfig,oemInfo);

                            data.put("qrCode",qrCode);

                            return ResultMessage.createSuccess(data);
                        } else {
                            return ResultMessage.createFail("支付失败");
                        }
                    } else {
                        log.info("支付宝扫码支付订单推送失败:{}");
                        return ResultMessage.createFail("支付失败");
                    }
                } else {
                    log.info("服务商信息错误");
                    return ResultMessage.createFail("服务商信息错误");

                }
            }



        } catch (Exception e) {
            log.error("支付宝js支付", e);
        }


        return ResultMessage.createFail("支付失败");
    }
}
